<template>
  <div v-if="isShow" :id="echartId" ref="Echarts" :key="echartKey" style="overflow: hidden;" :style="`height:${isInCard?'120':'300'}px`">
  </div>
  <el-scrollbar v-else><el-empty :description="emptyDes" :image-size="100" :image="emptyImage"/></el-scrollbar>
</template>
<script>
import { defineComponent, toRefs, reactive, onMounted,ref,watch,onActivated } from 'vue'
import * as echarts from 'echarts'
import { toThousands } from '@/utils/number-util'

export default defineComponent({
  name: 'BarEchat',
  props: {
    echartData: Object,
    echartId:String,
    emptyImage: { // 无数据时的图片
        type: String,
        required: false,
        default: ''
    },
    emptyDes: { // 无数据时的文案
        type: String,
        required: false,
        default: '暂无数据'
    },
    rightDownExplain: { // 右下角文案
        type: String,
        required: false,
        default: ''
    },
    isInCard: { //  是否在card中展示
        type: Boolean,
        required: false,
        default: false
    },
    isShowY: { //  是否展示y轴
        type: Boolean,
        required: false,
        default: false
    },
    isShowLegend: { //  是否展示图例
        type: Boolean,
        required: false,
        default: false
    },
    legendTextColor: { // 图例文字颜色
        type: String,
        required: false,
        default: '#666666'
    },
    yAxisName: { //  Y轴标题
        type: String,
        required: false,
        default: ''
    },
  },
  setup(props) {
    let echartKey = ref(Date.now())
    let isShow = ref(true)
    let seriesData = ref([])
    const state = reactive({
      option: {}
    })
    const renderEchartBar = () => {
      state.option = {
        tooltip: {
          trigger: 'axis',
          show:props.echartData.isShow != undefined && props.echartData.isShow == 0?false:true,
          confine: true,
          padding:10,
          extraCssText: "width:120px;white-space:pre",
          formatter: (params) => {
            let yData = props.echartData.yData
            let templete = ''
            let dataIndex = params[0].dataIndex //当前点击的柱子序号
            templete = props.echartData.xLable[dataIndex]?props.echartData.xLable[dataIndex]  + '\n':''
            for (let i = 0 ; i<yData.length; i++) {
              let item= yData[i];
              let name = item.label?item.label[dataIndex]:item.name
              name = name?name:'- '
              let nameString =  (item.data[dataIndex])?(name+ `: `+toThousands(item.data[dataIndex])+ (item.unit?item.unit:'')):(name+`: -`)
              templete+=nameString
              templete += (i != yData.length-1)? "\n":''
            }
            return templete
          },
        },
        color: ['#C09F88'],
        // 图例
        legend: {
          show: props.isShowLegend,
          left: 0,  // 或者使用像素值，例如 '50px'
          bottom: -6,
          itemHeight: 8,
          itemWidth: 15,
          textStyle: {
            color: props.legendTextColor,
          },
        },
        // 添加备注
        graphic: {
            type: 'text',
            right: 20,
            bottom: 0,
            style: {
                text: props.rightDownExplain,
                fill: '#999999',
                fontSize: 12,
                // 其他样式...
            },
        },
        grid: {
          //以div为中心 向右缩进30%
          left: props.yAxisName ? '3%' : '2%',
          right: "0%",
          top: props.isInCard ? "18%" : props.yAxisName ? '40' : '10%',
          bottom: props.rightDownExplain ? "10%" : "5%",
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: props.echartData.xData,
            axisLine: {
              lineStyle: {
                color: '#cfd1d3', // 坐标刻度线
                width:'0.5'
              },
            },
            axisLabel:{
              textStyle:{
                color:'#333333' // 标签文字
              }
            },
            axisTick: {		//Y轴刻度线
              show:false,
              alignWithLabel: true,
            }
          },
        ],
        yAxis:  [
            {
              name: props.yAxisName,
              nameTextStyle: {
                color: '#999999',
                align: 'right'
              },
              type: 'value',
              splitNumber:4,
              axisLabel:{
                show: props.echartData.xData.length > 7 || props.isShowY  ? true : false, //隐藏y轴
                formatter: (e) => {
                  let unit = props.echartData.yData[0].unit?props.echartData.yData[0].unit: ''
                  return e + unit

                },
                textStyle:{
                  color:"#999999"
                }
              },
              splitLine: {
                // show: props.echartData.xData.length > 7  ? true : false,
                length: 3,
                lineStyle:{
                  type:'dashed', //背景线条设置
                  color:"#EAEBEB"
                }
              },
              axisLine: {
                lineStyle: {
                  color: '#EAEBEB',
                },
              },
              axisTick: {		//Y轴刻度线
                show:false,
                alignWithLabel: true,
              },
            },
            {
              type: 'value',
              // min: 0,
              // max: 200,
              // interval: 50,
              splitNumber:3,
              axisLabel: {
                show: false, //隐藏y轴
              },
              splitLine: {
                show:false,
                lineStyle:{
                  type:'dashed', //背景线条设置
                  color:"#EAEBEB"
                }
              },
            }
        ],
        series: seriesData.value,
      }
    }
    const initeCharts = () => {
      let myChart = echarts.init(document.getElementById(props.echartId))
      // 绘制图表
      myChart.clear()
      myChart.setOption(state.option)
      window.addEventListener("resize", () => {myChart.resize()},true)
    }
    const packageSeriesData = () => {
      seriesData.value = []
      if(props.echartData.yData && props.echartData.yData.length > 0){
        let showNum = 0
        let isShowYAxis = true
        props.echartData.yData.forEach(function (item) {
          if(item.isShow){
            showNum = showNum + 1
            if(showNum > 1){
              if((item.unit && props.echartData.yData[0].unit) && (item.unit == props.echartData.yData[0].unit)){
                isShowYAxis = false
              } else if(!item.unit  && !props.echartData.yData[0].unit ){
                isShowYAxis = false
              }
            }
            console.log('isShowYAxis' + isShowYAxis)
            let series = {
              name: item.name,
              data: item.data,
              type: item.type,
              yAxisIndex:item.isShow && (showNum>1 && isShowYAxis)? 1: 0,
              barWidth: item.isShow ? '10' : '0',
              barMaxWidth:'10',
              barMinWidth:'0',
              barGap: '0',
              showBackground: false,
              symbolSize:5,
              itemStyle: {
                normal: {
                  color: item.type == 'line'?'#FF690A':'', //改变折线点的颜色
                  lineStyle: {
                    color: item.type == 'line'?'#FF690A':'' ,//改变折线颜色
                    width:1
                  },
                  //这里设置柱形图圆角 [左上角，右上角，右下角，左下角]
                  barBorderRadius: [2, 2, 2, 2],
                  label: {
                    show: item.isShow && item.type == 'bar' ? true : false, //开启数值显示显示
                    // show:false,
                    position: 'top', //在上方显示
                    formatter:function (params){
                      if(params.value && params.value >0){
                        return toThousands(params.value) + (item.unit?item.unit:'')
                      } else {
                        return ""
                      }
                    },
                    textStyle: { //数值样式
                      color: '#C09F88',
                      fontSize: 14
                    }
                  }
                }
              },
              backgroundStyle: {
                color: 'rgba(255, 255, 255, 0.1)',
              }
            }
            seriesData.value.push(series)
          }
        })
        renderEchartBar()

      }
    }
    onMounted(() => {
    })
    // onUnmounted(() => {
    //   myChart ?myChart.dispose():'' // （在图表容器被销毁之后，调用 echartsInstance.dispose 销毁实例）
    // })
    onActivated(() => {
      let myEchart = document.getElementById(props.echartId)
      if(myEchart){
        myEchart.removeAttribute('_echarts_instance_');
        setTimeout(() => {
                initeCharts()
              }, 200)
      }
    })
    watch(
        ()=>props.echartData,
        (val,preVal)=>{
          if(!val.yData || val.yData.length < 1) {
            isShow.value = false
          }else {
            isShow.value = true
            //val为修改后的值,preVal为修改前的值
            console.log("message",val,preVal)
            packageSeriesData()
            setTimeout(() => {
              initeCharts()
            }, 200)
            echartKey.value++
          }
        },
        {
          //如果加了这个参数，值为true的话，就消除了惰性，watch会在创建后立即执行一次
          //那么首次执行，val为默认值,preVal为undefined
          immediate:true,
          //这个参数代表监听对象时，可以监听深度嵌套的对象属性
          //比如message是一个对象的话，可以监听到message.a.b.c，也就是message下的所有属性
          deep:true,
        }
    )
    return {
      isShow,seriesData,...toRefs(state),echartKey
    }
  },
})
</script>

<style lang="scss" scoped>
#myEChartsBar {
  min-width: 31.25rem;
  min-height: 31.25rem;
  // max-height: 500px;
}
#myEChartsLine {
  max-height: 500px;
  // max-height: 400px;
  height: 500px;
}
</style>
